package com.lmt.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * 从服务提供者获取Message
 * Date 2018/07/21
 *
 * @author MT-Lin
 */
@RestController
public class GetMessageController {

    private Logger logger = LoggerFactory.getLogger(GetMessageController.class);

    private final LoadBalancerClient loadBalancerClient;

    private final RestTemplate restTemplate;

    @Autowired
    public GetMessageController(LoadBalancerClient loadBalancerClient, RestTemplate restTemplate) {
        this.loadBalancerClient = loadBalancerClient;
        this.restTemplate = restTemplate;
    }

    @RequestMapping("/getMessage")
    public String getMessage(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider-consul");
        logger.warn("consumer-consul->getMessage Service URI:{}", serviceInstance.getUri());
        logger.warn("consumer-consul->getMessage Service Name:{}", serviceInstance.getServiceId());
        String callServiceResult =
                restTemplate.getForObject(serviceInstance.getUri().toString() + "/getMessage", String.class);
        logger.warn("consumer-consul->getMessage callServiceResult:{}", callServiceResult);
        return callServiceResult;
    }
}
